package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.DebugGraphics;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import adaptors.QueryTableAdaptor;


import tools.Tab;
import tools.TabIO;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class SearchPanel extends javax.swing.JPanel implements ActionListener, ListSelectionListener, TableColumnModelListener, MouseListener	{
	private static final long serialVersionUID = 1L;
	private JComboBox searchTypeComboBox;
	private JButton newSearch;
	private JTextField searchTextField;
	private JButton openButton;
	private JTable qResultTable;
	private JScrollPane qResultScrollPane;
	private QueryTableAdaptor qResultTableModel;
	protected Tab selectedTab;
	
	private ArrayList<Tab> allTabs;
	private View parent;
	
	
	public SearchPanel(View parent) {
		super();
		this.parent = parent;
		initGUI();
	}
	
	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(768, 439));
			this.setLayout(null);
			{
				ComboBoxModel searchTypeComboBoxModel = 
						new DefaultComboBoxModel(new String[] { "Song Title", "Band Name" });
				searchTypeComboBox = new JComboBox();
				this.add(searchTypeComboBox);
				searchTypeComboBox.setModel(searchTypeComboBoxModel);
				searchTypeComboBox.setBounds(330, 11, 114, 22);
			}
			{
				qResultScrollPane = new JScrollPane();
				this.add(qResultScrollPane);
				qResultScrollPane.setBounds(48, 39, 708, 374);
				{
					qResultTableModel = 
							new QueryTableAdaptor(new String[] { "Band", "Song Title", "Rating" , "Tab Type" });
						QueryTableAdaptor qta = (QueryTableAdaptor)qResultTableModel;
						qta.setData(QueryTableAdaptor.blankTable());

						qResultTable = new JTable();						
						qResultScrollPane.setViewportView(qResultTable);
						qResultTable.setModel(qResultTableModel);
						TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(qResultTable.getModel());
						qResultTable.setRowSorter(sorter);
						ArrayList<SortKey> sortKeys = new ArrayList<SortKey>();
						sortKeys.add(new SortKey(2, SortOrder.ASCENDING));	// rating
						sortKeys.add(new SortKey(0, SortOrder.ASCENDING));	// band name
						sortKeys.add(new SortKey(1, SortOrder.ASCENDING));	// song name
						sorter.setSortKeys(sortKeys); 	
						
						qResultTable.getSelectionModel().addListSelectionListener(this);
						qResultTable.getColumnModel().addColumnModelListener(this);
						qResultTable.addMouseListener(this);
						setColumnWidths(parent.getSearchColumnWidths());
				}
			}
			{
				openButton = new JButton();
				this.add(openButton, "Center");
				openButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("view/icons/open-icon.png")));
				openButton.setActionCommand("openTab");
				openButton.setBorderPainted(false);
				openButton.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
				openButton.setBounds(12, 39, 24, 22);
				openButton.setToolTipText("Open Selected Tab...");
				openButton.addActionListener(this);
			}
			{
				newSearch = new JButton();
				this.add(newSearch, "Center");
				newSearch.setText("Search");
				newSearch.setActionCommand("newSearch");
				newSearch.setBounds(450, 11, 90, 22);
				newSearch.addActionListener(this);
			}
			{
				searchTextField = new JTextField();
				this.add(searchTextField);
				searchTextField.setBounds(48, 11, 276, 22);
				searchTextField.addActionListener(this);
				searchTextField.setActionCommand("searchText");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    public void fillTable (ArrayList<Tab> allTabs){
    	for(int x=0; x < allTabs.size(); x++){
    		Vector<Tab> v = new Vector<Tab>();
    		v.add(allTabs.get(x));
    		Tab tabArray[] = new Tab[allTabs.size()];
    		tabArray = allTabs.toArray(tabArray);
    		
    		//set allTabs locally so we can refer to it from the table selection listener
    		this.allTabs = allTabs;
    		
    		Object[][] data = QueryTableAdaptor.formatTableInformation(tabArray);
    		
    		((QueryTableAdaptor)qResultTableModel).setData(data);
    	}
    }
	
	public void setColumnWidths(int[] colWidths)	{
		for(int x=0; x < colWidths.length; x++)	{
			TableColumn tc = qResultTable.getColumnModel().getColumn(x);
			tc.setPreferredWidth(colWidths[x]);
		}

		((QueryTableAdaptor) qResultTable.getModel()).redrawTable();
	}

	public void doSearch(String text)	{
		parent.showSearchingWindow(true);
		parent.controller.performInternetSearch(searchTextField.getText());
		parent.showSearchingWindow(false);
	}
	
	public void clearSearchTable()	{
		QueryTableAdaptor qta = (QueryTableAdaptor)qResultTableModel;
		qta.setData(QueryTableAdaptor.blankTable());		
	}

	public void openTab()	{
		parent.showLoadingWindow(true);
		String s = TabIO.getTab(selectedTab.getAddress());
		selectedTab.setTabText(s);			
		parent.displayTab(selectedTab);
        parent.showLoadingWindow(false);
	}
	
	///////////////////////////////
	// Listeners from here down! //
	///////////////////////////////
	@Override
	public void actionPerformed( ActionEvent e )	{
		if( e.getActionCommand() == "newSearch" )	{
			doSearch(searchTextField.getText());
		}
		else if( e.getActionCommand() == "searchText" )	{
			doSearch(searchTextField.getText());
		}
		else if( e.getActionCommand() == "openTab" )	{
			openTab();
		}
	}
	
	@Override
	public void valueChanged(ListSelectionEvent event) {
        int viewRow = qResultTable.getSelectedRow();
        if (viewRow < 0) {
            //Selection got filtered away.
        } 
        else {
        	if( event.getValueIsAdjusting() )	// ignore mouse down action
        		return;							// only handle mouse up action below

        	// Handle Mouse Up Actions
        	int modelRow = qResultTable.convertRowIndexToModel(viewRow);
            System.out.println("Selected Row in model: " + modelRow);
            selectedTab = allTabs.get(modelRow);
        }
    }

	@Override
	public void columnAdded(TableColumnModelEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void columnMarginChanged(ChangeEvent arg0) {
		TableColumnModel tc = (TableColumnModel)arg0.getSource();

		int[] widths = new int[4];
		widths[0] = tc.getColumn(0).getPreferredWidth();
		widths[1] = tc.getColumn(1).getPreferredWidth();
		widths[2] = tc.getColumn(2).getPreferredWidth();
		widths[3] = tc.getColumn(3).getPreferredWidth();
		
		parent.saveColumnWidths(widths);
	}

	@Override
	public void columnMoved(TableColumnModelEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void columnRemoved(TableColumnModelEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void columnSelectionChanged(ListSelectionEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		if( arg0.getSource() instanceof JTable )	{
			if( arg0.getClickCount() == 2 )	{
				openTab();
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}
	
}
